package logic

import (
	"cart_srv/cart"
	"context"
	"fmt"
	"goods_srv/goods"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateCartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCartLogic {
	return &CreateCartLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateCartLogic) CreateCart(req *types.CreateCartRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 添加购物车

	//先查询商品是否存在
	findGoods, err := l.svcCtx.GoodsSrv.FindGoods(l.ctx, &goods.FindGoodsRequest{GoodsId: req.GoodsId})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	fmt.Println("id", findGoods.GoodsId)

	if findGoods.GoodsId != req.GoodsId {
		return &types.RegMsgResponse{
			Cre:  -2,
			Msg:  "商品不存在",
			Data: nil,
		}, err
	}
	//判断库存
	if findGoods.GoodsStock < req.Num {
		return &types.RegMsgResponse{
			Cre:  -2,
			Msg:  "库存不足",
			Data: nil,
		}, err
	}

	//模拟用户登录
	userId := 1

	//添加购物车
	createCart, err := l.svcCtx.CartSrv.CreateCart(l.ctx, &cart.CreateCartRequest{
		UserId:      int64(userId),
		GoodsId:     req.GoodsId,
		GoodsTitle:  findGoods.GoodsTitle,
		GoodsPrice:  findGoods.GoodsPrice,
		Num:         req.Num,
		GoodsAvatar: findGoods.GoodsCover,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -3,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}
	return &types.RegMsgResponse{
		Cre: 0,
		Msg: "添加成功",
		Data: map[string]interface{}{
			"cartId": createCart.CartId,
		},
	}, err
}
